import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags } from '@nestjs/swagger';
import { PropertyService } from './property.service';
import { UserGuard } from 'src/role/role.guard';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { DeptService } from 'src/dept/dept.service';
import { In } from 'typeorm';
import { NotFound } from 'src/util/http';
import { UseLog } from 'src/log/useLog.decorator';

@Controller('api/property')
@ApiTags("资产管理")
@UseGuards(AuthGuard("jwt"))
export class PropertyController {
    constructor(
        private readonly propertyService: PropertyService,
        private readonly deptService: DeptService
    ) { }

    @Post("add")
    @ApiTags("添加资产")
    @UseGuards(UserGuard([]))
    public async add(
        @CurrentUser() user: UserSys,
        @Body() { depts, ...rest }
    ) {
        const entity = this.propertyService.property.create({
            ...rest,
            user,
            updUser: user,
            system: user.system,
            depts: await this.deptService.dept.find({ where: { id: In(depts) } }),
        })
        await this.propertyService.property.save(entity);
    }

    @Post(":id/upd")
    @ApiTags("修改资产")
    @UseGuards(UserGuard())
    public async upd(
        @CurrentUser() user: UserSys,
        @Body() { depts, ...rest },
        @Param("id") id: number
    ) {
        const entity = await this.propertyService.property.findOne({ where: { id } });
        if (!entity) throw NotFound
        const deptList = await this.deptService.dept.find({ where: { id: In(depts) } });
        await this.propertyService.property.save({
            ...entity,
            ...rest,
            depts: deptList,
            updUser: user,
        })
    }

    @Get("get")
    @ApiTags("获取资产")
    @UseGuards(UserGuard())
    public async get(
        @CurrentUser() user: UserSys
    ) {
        return await this.propertyService.property.find({
            relations: ["system", "user", "updUser", "depts"],
            order: {
                id: "DESC"
            }
        })
    }
    
    @Post("del")
    @UseLog("删除资产")
    del(
        @Body() { ids }
    ) {
        return this.propertyService.property.delete({
            id: In(ids)
        })
    }

}
